use std::path::PathBuf;
use rbatis::RBatis;
use once_cell::sync::Lazy;
use anyhow::Result as DbResult;

static RB: Lazy<RBatis> = Lazy::new(|| RBatis::new());

pub fn rb() -> &'static RBatis { &RB }

fn get_data_dir() -> DbResult<PathBuf> {
    let mut data_dir = dirs::data_dir().ok_or_else(|| anyhow::anyhow!("无法获取数据目录"))?;
    data_dir.push("tauri-call");
    Ok(data_dir)
}

fn sqlite_url() -> DbResult<String> {
    let data_dir = get_data_dir()?;
    std::fs::create_dir_all(&data_dir)?;
    let db_path = data_dir.join("call_history.db");
    log::info!("数据库路径: {}", db_path.display());
    Ok(format!("sqlite://{}", db_path.to_string_lossy()))
}

pub fn init_database() -> DbResult<()> {
    tauri::async_runtime::block_on(async move {
        let url = sqlite_url()?;
        RB.init(rbdc_sqlite::driver::SqliteDriver {}, &url)?;
        RB.exec(
            r#"
            CREATE TABLE IF NOT EXISTS call_records (
                id TEXT PRIMARY KEY,
                target TEXT NOT NULL,
                target_display TEXT NOT NULL,
                call_type TEXT NOT NULL,
                status TEXT NOT NULL,
                timestamp INTEGER NOT NULL,
                duration INTEGER
            )
            "#,
            vec![],
        ).await?;
        RB.exec("CREATE INDEX IF NOT EXISTS idx_timestamp ON call_records(timestamp)", vec![]).await?;
        RB.exec("CREATE INDEX IF NOT EXISTS idx_target ON call_records(target)", vec![]).await?;
        // contacts table
        crate::repositories::contact_repository::ContactRepository::init_table().await?;
        log::info!("数据库表初始化完成");
        Ok(())
    })
}


